<template>
    <el-form ref="ruleFormRef" style="max-width: 500px" :model="ruleForm" :rules="rules">

        <el-form-item label="学科" prop="name">
            <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="年级" prop="level">
            <el-select v-model="ruleForm.level" placeholder="请选择年级" @change="levelChange">
                <el-option :label="item.name" :value="item.value" v-for="item in levelStore.list" :key="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { type FormInstance,type FormRules,ElMessage } from 'element-plus'
import { useLevelStore } from '@/stores/level'
import { subjectAdd,type subjectParamsAddType } from '@/api/jiaoyu'
import { useRouter } from 'vue-router';

// 创建路由实例
const router = useRouter()

const levelStore = useLevelStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<subjectParamsAddType>({
    name: '',
    level: '',
    id: null,
    levelName:""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = ref<FormRules<subjectParamsAddType>>({
    name: [
        { required: true, message: 'Please input Activity name', trigger: 'blur' },
        { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    level: [
        {
            required: true,
            message: 'Please select',
            trigger: 'change',
        },
    ]
})

function levelChange(val:any){
const level = levelStore.list.find(item => item.value == val)
ruleForm.value.levelName = (level?.name as string)
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm.value);
            subjectAdd(ruleForm.value).then(res => {
                if(res.code === 1){
                    ElMessage({
                        message: '提交成功',
                        type: 'success'
                    })
                    router.push('/xuekelist')
                }else{
                    ElMessage({
                        message: res.message,
                        type: 'error'
                    })
                }
            })
          
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>